
var coupons = "";
var detail = "";
var cardlist = [];
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var app = getApp();
var paymethod = '';
var payresult = "";
var strCardNo = "";
var ActivityGoodsOrderSign = ""
var ActivityGoodsOrderCardSign = "";
var OrderGoodsDetailID = "";
var PayTotalPrice = "";
/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var total_micro_second = 5 * 60 * 1000;

/* 毫秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止",
      issuccess: false,
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that);
  }
    , 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return min + "分" + sec + "秒";
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clock: '',//支付剩余时间
    year: '',//当前的年份
    chkzuolist: [],//选择的座位
    chkzuo: '',//选择的座位
    payforprice: 0,//付钱价格
    piaoprice: 0,//票价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    chkday: '',//日期
    changciid: '',//场次id
    time: '',//开场时间
    lingshilist: [],//零食列表
    zhifuqian: 0,//支付的钱
    open: false,//列表选项
    items: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
 
    payresult = JSON.parse(options.payresult)
    detail = app.globalData.tempactivitydetail;
    console.log("++++++++++++========")
    console.log(detail)
    this.setData({ detail, payresult, phone: app.globalData.loginuserinfo.mobile })
    return req.CardList(app.globalData.token).then(res => {
      console.log(res)
      cardlist = res.data.data;
      console.log(cardlist);
      if (cardlist.length > 0) {
        this.setData({ hascard: true })
        paymethod = 0;
        for (var i = 0; i < cardlist.length; i++) {
          cardlist[i].cardNostart = cardlist[i].Mcode.substring(0, 4) + "****" + cardlist[i].Mcode.substr(cardlist[i].Mcode.length - 2, cardlist[i].Mcode.length)
        }
      }

      this.setData({ cardlist: cardlist })
    }).then(()=>{
      //TODO 计算活动价
      // EventDiscountTarget, EventDiscountType, EventDiscountValue, PriceService, tickcount, PriceSale, EventDiscountThreshold
      return req.CalculateActivityPrice(detail.EventDiscountTarget, detail.EventDiscountType, detail.EventDiscountValue, detail.PriceService, detail.buynum, detail.PriceSale, detail.EventDiscountThreshold).then(res=>{
        console.log(res)
        PayTotalPrice = res.data.pricetotal;
        this.setData({ PayTotalPrice})
      })
    })
    //结束标识符
  },


  radioChange: function (e) {
    console.log(e)
    paymethod = e.detail.value;
  },

  paynow: function () {
    OrderGoodsDetailID="";
    for (var i = 0; i < payresult.taborder.length; i++) {
      if (i == payresult.taborder.length - 1) {
        OrderGoodsDetailID = OrderGoodsDetailID+ payresult.taborder[i].OrderGoodsDetailID+''
      } else {
        OrderGoodsDetailID = OrderGoodsDetailID+payresult.taborder[i].OrderGoodsDetailID+","
      }
     
    }
    
    if (paymethod ==='') {
      wx.showModal({
        title: '提示',
        content: '请选择支付方式',
      })
    } else if (paymethod == 'wxpay') {
      //TODO 微信支付
      // orderTicketID, OrderGoodsDetailID,
      // LinkTelcode, coupons, PayTotalPrice, sign, token
      if (PayTotalPrice === ""){
        wx.showModal({
          title: '提示',
          content: '支付失败请稍候再试',
        })
        return false;
      }
      console.log('微信支付');
      var paysign = "OrderTicketID=" + payresult.tab[0].OrderTicketID + "OrderGoodsDetailID=" + OrderGoodsDetailID + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "coupons=" + coupons + "" + "" + "PayTotalPrice="+ PayTotalPrice  + ""
      return req.GetSignStr(paysign).then(res => {
        if (res.data.success) {
          ActivityGoodsOrderSign = res.data.data;
        }
      }).then(() => {
        console.log(app.globalData.token)

        return req.GetMiniGoodsAppPaySign(payresult.tab[0].OrderTicketID, OrderGoodsDetailID, app.globalData.loginuserinfo.mobile, "",PayTotalPrice,ActivityGoodsOrderSign, app.globalData.token).then(res => {

          console.log(res)
          var pay = res.data
          //发起支付   
          var timeStamp = pay.TimeStamp;
          console.log("timeStamp:" + timeStamp)
          var packages = pay.Package;
          console.log("package:" + packages)
          var nonceStr = pay.NonceStr;
          console.log("nonceStr:" + nonceStr)
          var paySign = pay.PaySign;
          console.log("paySign:" + paySign)
          var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
          //调用支付
          // pay(param)
          console.log("支付")
          wx.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: param.package,
            signType: param.signType,
            paySign: param.paySign,
            success: function (res) {
              // 业务逻辑
              console.log("支付成功")
  //TODO 购买成功 跳转到 订单
  wx.showToast({
    title: '支付成功',
    success:function(){
      setTimeout(function () {
        // 放在最后--
        wx.reLaunch({
          url: '../member/activityOrder',
        })
      }
        , 1000)
   
    }
  })
          
         
            }, fail: function (error) {
              console.log(error)
            }
          })
        })
      })


    }
    else {  //TODO 会员卡支付
      console.log(cardlist)
      console.log('会员支付');
      wx.showLoading({
        title: '支付中',
        mask: true
      })
      if (PayTotalPrice === "") {
        wx.showModal({
          title: '提示',
          content: '支付失败请稍候再试',
        })
        return false;
      }
      // strCardNo = cardlist[paymethod].Mcode;
      var paysign = "OrderTicketID=" + payresult.tab[0].OrderTicketID + "OrderGoodsDetailID=" + OrderGoodsDetailID + "wxopenID=ooORTwu9F9-roa7PI74rHIWfjuvA" + "mphone=" + app.globalData.loginuserinfo.mobile + "" + "LinkTelcode=" + app.globalData.loginuserinfo.mobile + "" + "coupons=" + coupons + "" + "PayTotalPrice="+PayTotalPrice
      return req.GetSignStr(paysign).then(res => {
        if (res.data.success) {
          ActivityGoodsOrderCardSign = res.data.data;
        }
      }).then(() => {
        // 发起支付
        return req.ActivityGoodsOrder(payresult.tab[0].OrderTicketID, OrderGoodsDetailID, "", app.globalData.loginuserinfo.mobile, app.globalData.loginuserinfo.mobile,"", PayTotalPrice, ActivityGoodsOrderCardSign, app.globalData.token).then(res => {
          console.log(res)
          var result = res.data.data
          // if (res.data.success) {
          //跳转到支付成功页面
          if (res.data.success) {
            wx.showToast({
              title: '支付成功',
              success: function () {
                setTimeout(function () {
                  // 放在最后--
                  wx.reLaunch({
                    url: '../member/activityOrder',
                  })
                }
                  , 1000)
              }
            })
          
            //TODO 支付成功 跳转订单页面
       
          } else {
            wx.showModal({
              title: '提示',
              content: '会员卡支付失败',
            })
            setTimeout(function () {
              // 放在最后--
              wx.hideLoading();
            }
              , 1600)
            return false;
          }

        })
      })
    }
  },
  goback: function () {
    //TODO返回详情
    wx.switchTab({
      url: '../huodong/index',
    })
  },

  onShow:function(){
    paymethod =""
  }
})